<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      :success-text="successText"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <articleItem
          v-for="(item, index) in list"
          :key="index"
          :article="item"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import { getArticleList } from "@/api/article";
import articleItem from "@/components/article-item";
export default {
  data() {
    return {
      list: [], // 存储列表数据的数组
      loading: false, // 控制加载中 loading 状态
      finished: false, // 控制数据加载结束的状态
      timestamp: +new Date(), // 请求数据中的时间戳
      isLoading: false, // 下拉刷新的状态控制
      successText: "", //刷新成功的提示
      error: false
    };
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  components: {
    articleItem
  },
  methods: {
    // 加载数据
    async onLoad() {
      try {
        let { data: res } = await getArticleList({
          channel_id: this.channel.id,
          timestamp: this.timestamp,
          with_top: 0
        });
        console.log(res);
        // 追加数据
        this.list.push(...res.data.results);
        // 修改时间戳
        this.timestamp = res.data.pre_timestamp;
        // 修改加载状态
        this.loading = false;
        // 判断结束条件
        if (res.data.results.length < 10) {
          this.finished = true;
        }
      } catch (error) {
        this.$toast.fail("加载失败");
        this.error = true;
      }
    },
    // 下拉刷新
    async onRefresh() {
      let { data: res } = await getArticleList({
        channel_id: this.channel.id,
        timestamp: +new Date(),
        with_top: 0
      });
      // 追加数据
      this.list.unshift(...res.data.results);
      this.successText = `为您刷新了${this.list.length}条数据`;
      // 修改加载状态
      this.isLoading = false;
    }
  }
};
</script>

<style scoped lang="less">
.article-list {
  overflow-y: scroll;
  height: 79vh;
}
</style>
